<template>
  <div class="vaccine-form">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <h2>{{ isEdit ? '编辑疫苗记录' : '添加疫苗记录' }}</h2>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="form-container"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="宠物编号" prop="petId">
              <el-input v-model.number="formData.petId" placeholder="请输入宠物编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="疫苗类型" prop="vaccineType">
              <el-input v-model="formData.vaccineType" placeholder="请输入疫苗类型" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="vaccineBrand">
              <el-input v-model="formData.vaccineBrand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接种日期" prop="vaccineDate">
              <el-date-picker
                v-model="formData.vaccineDate"
                type="date"
                placeholder="选择接种日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="有效期" prop="expiryDate">
              <el-date-picker
                v-model="formData.expiryDate"
                type="date"
                placeholder="选择有效期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次接种提醒日期" prop="reminderDate">
              <el-date-picker
                v-model="formData.reminderDate"
                type="date"
                placeholder="选择下次接种提醒日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="接种机构或兽医" prop="vaccineAdministered">
              <el-input v-model="formData.vaccineAdministered" placeholder="请输入接种机构或兽医" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { vaccineApi } from '@/api'
import type { Vaccine } from '@/types'

const router = useRouter()
const route = useRoute()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const formData = reactive<Vaccine>({
  vaccineId: undefined,
  petId: undefined,
  vaccineType: '',
  vaccineBrand: '',
  vaccineDate: '',
  expiryDate: '',
  reminderDate: '',
  veterinarianName: '',
  vaccineAdministered: ''
})

// 表单验证规则
const formRules: FormRules = {
  vaccineType: [
    { required: true, message: '请选择疫苗类型', trigger: 'change' }
  ],
  vaccineBrand: [
    { required: true, message: '请输入疫苗品牌', trigger: 'blur' }
  ],
  vaccineDate: [
    { required: true, message: '请选择接种日期', trigger: 'change' }
  ],
  expiryDate: [
    { required: true, message: '请选择失效日期', trigger: 'change' }
  ],
  reminderDate: [
    { required: true, message: '请选择提醒日期', trigger: 'change' }
  ],
  veterinarianName: [
    { required: true, message: '请输入医生姓名', trigger: 'blur' }
  ],
  vaccineAdministered: [
    { required: true, message: '请输入疫苗接种人员', trigger: 'blur' }
  ]
}

// 获取疫苗记录详情
const fetchVaccineDetail = async (id: number) => {
  try {
    const response = await vaccineApi.getById(id)
    if (response.code === 200) {
      Object.assign(formData, response.data)
    } else {
      ElMessage.error(response.message || '获取疫苗记录详情失败')
    }
  } catch (error) {
    console.error('获取疫苗记录详情失败:', error)
    ElMessage.error('获取疫苗记录详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    console.log('提交的疫苗数据:', formData)
    console.log('提交的疫苗数据类型:', typeof formData)
    console.log('提交的疫苗数据JSON:', JSON.stringify(formData, null, 2))
    console.log('是否为编辑模式:', isEdit.value)
    console.log('API调用类型:', isEdit.value ? 'update' : 'add')
    
    let response
    if (isEdit.value) {
      response = await vaccineApi.update(formData)
    } else {
      response = await vaccineApi.add(formData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      router.push('/medical-manage/vaccine')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    console.error('错误详情:', error.response?.data || error)
    console.error('错误状态码:', error.response?.status)
    console.error('错误状态文本:', error.response?.statusText)
    console.error('错误响应数据:', error.response?.data)
    
    // 显示更详细的错误信息
    if (error.response?.data?.message) {
      ElMessage.error(`提交失败: ${error.response.data.message}`)
    } else if (error.response?.status === 500) {
      ElMessage.error('服务器内部错误，请检查提交的数据格式')
    } else {
      ElMessage.error('提交失败，请检查网络或表单数据')
    }
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/medical-manage/vaccine')
}

onMounted(() => {
  if (isEdit.value) {
    const vaccineId = Number(route.params.id)
    if (vaccineId) {
      fetchVaccineDetail(vaccineId)
    }
  }
})
</script>

<style scoped>
.vaccine-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}
</style> 